<?php
/*
 * Unfavorite a recipe.
 */

// authenticate user first
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  // authentication failed
  return;
}

if (!F3::exists("PARAMS['user_id']") || !F3::exists("PARAMS['recipe_id']")):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Need both a user id and a recipe id.");
	echo json_encode($err);
	return;
endif;

// get user ID from session
$id = F3::get('SESSION.user_id');
$uid = F3::get("PARAMS['user_id']");
if($id!=F3::get("PARAMS['user_id']")):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Given user id $uid does not match authenticated user $id.");
	echo json_encode($err);
	return;
endif;

// does recipe exist?
$rid = F3::get("PARAMS['recipe_id']");
$param = array('1'=>$rid);
$result = DB::sql("SELECT rid from recipes where rid = ?", $param);
if(count($result)==0):
	//the recipe doesn't exist
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Recipe does not exist.");
	echo json_encode($err);
	return;
endif;

// unfavorite recipe
$param = array('1'=>$id, '2'=>$rid);
DB::sql("delete from favorites where uid = ? and rid = ?",$param);

// success
header('HTTP/1.1 204');
header("Content-Type: application/json");
$response = "success";
echo json_encode($response);
return;
?>
